#!/usr/bin/python
import psycopg2
import sys

def writeHtml(records):
    text = "\n"
    for row in records:
        text += row[1] + "<br/>\n"             

    f = open(r'/tmp/template.txt')
    template = f.read()
    f.close()
    html = template.replace('$n1', text);     
        
    f = open('/tmp/temp.html', 'w')
    f.write(html)
    f.close()    
   

def main():
    #start of script
    #Define our connection string
    conn_string = "host='localhost' dbname='versusdb' user='postgres' password='postgres'"
    # print the connection string we will use to connect
    print "Connecting to database\n    ->%s" % (conn_string)
    try:        
        conn = psycopg2.connect(conn_string)
        cursor = conn.cursor()
        print "DB connected!"
        cursor.execute("SELECT * FROM product")
        records = cursor.fetchall()
        # print "\nShow me the databases:\n"
        writeHtml(records)
        print "done!"
    except:
        # Get the most recent exception
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        # Exit the script and print an error telling what happened.
        sys.exit("Database connection failed!\n ->%s" % (exceptionValue))


if __name__ == "__main__":
    sys.exit(main())